package com.hb.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hb.guli.service.edu.entity.Subject;
import com.hb.guli.service.edu.entity.excel.ExcelSubject;
import com.hb.guli.service.edu.mapper.SubjectMapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@AllArgsConstructor // 全参构造函数
@NoArgsConstructor  // 无参构造函数
public class ExcelSubjectListener extends AnalysisEventListener<ExcelSubject> {

    private SubjectMapper subjectMapper;

    @Override
    public void invoke(ExcelSubject excelSubject, AnalysisContext analysisContext) {
        log.info("解析到的每一行:{}", excelSubject);
        // 处理读取出来的数据
        String levelOneTitle = excelSubject.getLevelOneTitle();
        String levelTwoTitle = excelSubject.getLevelTwoTitle();

        // 组装一级类别
        Subject subjectOne = this.getSubjectByTitle(levelOneTitle);
        if(subjectOne == null){
            subjectOne = new Subject();
            subjectOne.setParentId("0");
            subjectOne.setTitle(levelOneTitle);
            subjectMapper.insert(subjectOne);
        }
        // 组装二级类别
        Subject subjectTow = getSubjectByTitle(levelTwoTitle, subjectOne.getId());
        if(subjectTow == null){
            subjectTow = new Subject();
            subjectTow.setParentId(subjectOne.getId());
            subjectTow.setTitle(levelTwoTitle);
            subjectMapper.insert(subjectTow);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("全部数据解析完成");
    }

    /**
     * 跟据分类名称查询是否存在
     * @param title
     * @return
     */
    private Subject getSubjectByTitle(String title) {
        return getSubjectByTitle(title,"0");
    }


    /**
     * 跟据分类名称查询是否存在
     * @param title
     * @return
     */
    private Subject getSubjectByTitle(String title,String parentId) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", parentId);
        return subjectMapper.selectOne(queryWrapper);
    }
}
